//
//  HomeTableViewController.swift
//  MicroBlog
//
//  Created by QT on 15/7/28.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {
    
    private var statuses: [status]?{
        didSet{
            // 当接受到数据，刷新表格
            tableView.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        if !UserAccount.userLogon{
            vistorView?.setUpInfo(true, message: "关注一些人，回这里看看有什么惊喜", imgName: "visitordiscover_feed_image_smallicon")
            return
        }


        refreshControl = HMRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // MARK: - 添加通知
        // 添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "SelectedPicture:", name: HMpictureViewNotification, object: nil)
        
        
        prepareTableView()
        loadData()
//
   }
    
    
    
// MARK: -保存数据的变量
    private var pictureView: statusPictureView?
    private var presentIndex: NSIndexPath?
// MARK: -转场图片视图
    private var tranImgView: UIImageView = {
       let img = UIImageView()
        img.contentMode = UIViewContentMode.ScaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    
    @objc private func SelectedPicture(notificatin: NSNotification){
        // 接收到通知，modal 新控制器，显示图片
        // 1.对数据进行判断
        guard let urls = notificatin.userInfo![HMPictureViewNotificationInfoURL] as? [NSURL] else{
            print("路径不存在")
            return
        }
        guard let indexPath = notificatin.userInfo![HMPictureViewNotificationInfoIndexPath] as? NSIndexPath else{
            print("indexPath不存在")
            return
        }
        guard let picView = notificatin.object as? statusPictureView else{
            print("图像视图不存在")
            return
        }
        
        // 保存图像视图
        pictureView = picView
        // 设置转场视图的内容
        tranImgView.sd_setImageWithURL(urls[indexPath.item])
        // 记录当前索引
        presentIndex = indexPath
        
         let picBrowser = HMPictureBrowserController(urls: urls, index: indexPath.row)
        
        // 自定义转场动画
        picBrowser.transitioningDelegate = self
        picBrowser.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(picBrowser, animated: true, completion: nil)
    }
    
    
        private func prepareTableView(){
            // 注册cell
            tableView.registerClass(statusNormalCell.self, forCellReuseIdentifier: statusCellIdentifier.NormalCell.rawValue)
            tableView.registerClass(statusForwardCell.self, forCellReuseIdentifier: statusCellIdentifier.ForwardCell.rawValue)
            ////
            ////
            //        tableView.rowHeight = 400
            ////        tableView.rowHeight = UITableViewAutomaticDimension
            tableView.estimatedRowHeight = 300
            tableView.separatorStyle = UITableViewCellSeparatorStyle.None
            
            refreshControl = HMRefreshControl()
            refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        }
      
        

    private var pullUpRefresh = false
    func loadData(){
        
        refreshControl?.beginRefreshing()
//        automaticallyAdjustsScrollViewInsets
        // 开始加载
        
        // since_id
        var since_id = statuses?.first?.id ?? 0
        
        var  max_id = 0
        if pullUpRefresh{
            // 上拉刷新
            since_id = 0
            max_id = statuses?.last?.id ?? 0
            print("***********")
            print(max_id)
        }
        // 复位刷新
        pullUpRefresh = false
        
        status.loadStatus(since_id,max_id: max_id) {(datalist, error) -> () in
            
            // 结束加载
            self.refreshControl?.endRefreshing()
            
            if error != nil{
                print(error)
                return
            }
          
            let count = datalist!.count
            print("刷新到\(count)条数据")
            
            if since_id > 0{
                
                self.showPullDownTip(count)
            }
            
            if count == 0{
                return
            }
            // since_id > 0 下拉刷新
            if since_id > 0{
                self.statuses =  datalist! + self.statuses!
            }else if max_id > 0{
                self.statuses = self.statuses! + datalist!
            }else{
                self.statuses = datalist
            }
        }
    }

    // 显示下拉刷新提示
    private func showPullDownTip(count: Int){
        
        // TODO: 取不到animationKeys??? DONE
        if tipLab.layer.animationForKey("position") != nil{
            // 有动画在执行
            print("动画正在执行中")
            return
        }
        
        
        tipLab.text = count == 0 ? "没有新微博" : "刷新\(count)条微博"
        
        print(tipLab.frame)
        
        let h: CGFloat = 44
        let tipRect = tipLab.frame
        UIView.animateWithDuration(1, animations: { () -> Void in
            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLab.frame = CGRectOffset(self.tipLab.frame, 0, 3 * h)
            }) { (_) -> Void in
              // 复位tipLab原始位置
                self.tipLab.frame = tipRect
        }
        
    }
    
    // 懒加载刷新提示标签
    private lazy  var tipLab: UILabel = {
        let h: CGFloat = 44
        let tipLab = UILabel(frame: CGRect(x: 0, y: -2 * h, width: UIScreen.mainScreen().bounds.width, height: h))
        
        tipLab.backgroundColor = UIColor.orangeColor()
        tipLab.textAlignment = NSTextAlignment.Center
        tipLab.font = UIFont.systemFontOfSize(13)
        tipLab.textColor = UIColor.darkGrayColor()
        
        self.navigationController?.navigationBar.insertSubview(tipLab, atIndex: 0)

        return tipLab
    }()
    
//   数据源方法
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statuses?.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let sta = statuses![indexPath.row]
        print(sta.id)
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellIdentifier.cellID(sta), forIndexPath: indexPath) as! statusCell
        
        cell.Status = sta
        
        if indexPath.row == (self.statuses?.count)! - 1{
            pullUpRefresh = true
            loadData()
        }
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 获取模型
        let status =  statuses![indexPath.row]
        
        if let height = status.rowheigh{
            return height
        }
        
        // 获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellIdentifier.cellID(status)) as! statusCell
//        let cell = tableView.cellForRowAtIndexPath(indexPath) as! statusCell

        status.rowheigh = cell.getRowHeight(status)
        return status.rowheigh!
    }

}



private var isPresent: Bool = false
// MARK: - 自定义转场需要遵守的协议
extension HomeTableViewController: UIViewControllerTransitioningDelegate{
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self
    }
}
extension HomeTableViewController: UIViewControllerAnimatedTransitioning{
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 1
    }
    
    // transitionContext: 提供了动画转场需要的元素
        // transitionContext: 动画结束后必须调用的
        // containerView: 容器视图
        // viewForKey(8.0): 可以获取到动画转场的视图
        // controllerForKey: 获取转场的控制器
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//        let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
//        let toVc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
//        
//        print(fromVc)
//        print(toVc)
        
        if isPresent {
            // 获取toView
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            // 将试图添加到容器
//            transitionContext.containerView()?.addSubview(toView)
            // 设置动画
//            toView.alpha = 0
            // 转场视图添加到容器
            transitionContext.containerView()?.addSubview(tranImgView)
            // 起始位置
            let startF = pictureView?.getSmallPicFrame(presentIndex!)
            let endF = pictureView?.getFullScreenSize(presentIndex!)
            tranImgView.frame = startF!
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//                toView.alpha = 1
                    self.tranImgView.frame = endF!
                              }) { (_) -> Void in
                   
                self.tranImgView.removeFromSuperview()
                transitionContext.containerView()?.addSubview(toView)
                transitionContext.completeTransition(true)
            }
 
        }else{
            let formView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                formView.alpha = 0
                }, completion: { (_) -> Void in
                    formView.removeFromSuperview()
                     transitionContext.completeTransition(true)
            })
        }
        
        
    }
}
